package com.imyours.net.messagedisposer;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.imyours.model.Friend;
import com.imyours.model.Team;
import com.imyours.net.result.ExecuteResult;
import com.imyours.net.result.FriendListResult;

public class TeamListMessageDisposer extends MessageDisposer {

	public TeamListMessageDisposer(ExecuteResult result, String text) {
		super(result, text);
	}

	@Override
	protected void execute(JSONObject jo) throws Throwable {
		JSONArray ja = jo.getJSONArray("teams");
		List<Team> teamList = new ArrayList<Team>();
		Team team = null;
		Friend friend = null;
		JSONObject friendJO = null;
		for (int i = 0; i < ja.size(); i++) {
			team = new Team();
			team.setId(ja.getJSONObject(i).getLong("id"));
			team.setName(ja.getJSONObject(i).getString("name"));
			team.setOrder(ja.getJSONObject(i).getInt("order"));
			team.setFriends(new ArrayList<Friend>());
			for (int j = 0; j < ja.getJSONObject(i).getJSONArray("users").size(); j++) {
				friendJO = ja.getJSONObject(i).getJSONArray("users").getJSONObject(j);
				friend = new Friend();
				friend.setId(friendJO.getLong("id"));
				friend.setName(friendJO.getString("nickName"));
				team.getFriends().add(friend);
			}
			teamList.add(team);
		}
		((FriendListResult) result).setTeams(teamList);
		result.setSuccessed(true);
	}
}
